const Router = require('koa-router');
const router = new Router();
const tool = require('../../tools/tool')
const {db, QueryTypes} = require("../../models/db");

// 点击区域名称查询要派送的单据
router.post('/deliver/getOrderByAreaId', async ctx => {
    let tenantId = ctx.user.tenantId

    let beginDate = ctx.request.body.beginDate;
    let endDate = ctx.request.body.endDate;
    let searchTxt = ctx.request.body.searchTxt;
    let areaId = ctx.request.body.areaId;
    let scanBillId = ctx.request.body.scanBillId;
    let ret = {
        list: [],
        cargo: {}
    };
    let options = {type: QueryTypes.SELECT}
    if (scanBillId) {
        let teants = await tool.relCompany(tenantId);
        if(teants.length > 0) {
            let tids = teants.join(',');
            let sql = `select a.id,a.billState,a.tenantName,a.billType,a.qty totalQty,a.buName,a.tenantName,a.billDate,a.billNo,a.transTypeName,a.transType,a.address,isnull(c.state, 0) loadState,a.areaName, a.areaId 
            from (
                SELECT a.*,b.name buName,c.name tenantName,b.address,isnull(ar.name, '未定位') areaName,b.areaId  from invoice a inner join contact b on a.buId=b.id and a.tenantId in(${tids}) and a.id=${scanBillId} 
                                         inner join tenant c on a.tenantId=c.id left join area ar on b.areaId=ar.id
            ) a left join cargo_invoice c on a.id=c.iid   order by a.tenantId,a.buName,a.billDate  ;
            `
            let list = await db.query(sql, options)
            if (list.length === 0) {
                return ctx.err('未找到数据');
            }
            if (list[0].billType !== 'SALE') {
                return ctx.err('非销售票据');
            }
            if (list[0].loadState == 1) {
                return ctx.err('该单据已装货');
            }
            if (list[0].loadState == 2) {
                return ctx.err('该单据已送货');
            }
            if (list[0].billState === 'del') {
                return ctx.err('此票据已被删除，无法扫描');
            }
            ret.list = list
        }
        else {
            return ctx.err('请先关联配送公司')
        }
    }
    else {
        let sqls = '';
        if (searchTxt) {
            sqls = `select a.*,b.name tenantName from (
                SELECT * from v_invoice where tenantId in(SELECT companyId tenantId from tenant_company where tenantId=${tenantId}) and billDate between ${beginDate} and ${endDate} and billType='SALE' and
                 isLoad=0  and (buName like '%${searchTxt}%' or billNo like '%${searchTxt}%')
            ) a INNER JOIN tenant b on a.tenantId=b.id order by a.tenantId,a.buName,a.billDate`
        }
        else {
            sqls = `select a.id,a.buName,a.buId,a.areaId,a.areaName,a.transTypeName,a.billNo,a.billDate,a.address,a.totalQty,b.name tenantName from (
                    SELECT * from v_invoice where tenantId in(SELECT companyId tenantId from tenant_company where tenantId=${tenantId}) and billDate between ${beginDate} 
                        and ${endDate} and areaId=${areaId} and billType='SALE'  and isLoad=0
                ) a INNER JOIN tenant b on a.tenantId=b.id order by a.tenantId,a.buName ,a.billDate `
        }
        ret.list = await db.query(sqls, options)
    }
    if (ret.list.length === 0) {
        return ctx.err("未找到数据");
    }
    if (areaId) {
        ret.cargo = await db.models['cargo'].findOne({
            where: {
                tenantId,
                areaId,
            },
            order: [['id', 'desc']]
        })
    }
    return ctx.suc('', ret);
})


module.exports = router;
